<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片布局 -->
    <el-card>
      <el-button type="primary" @click="addroledialog">添加角色</el-button>
      <el-table :data="rolelist" border stripe="">
        <!-- 展开列 -->
        <el-table-column type="expand">
            <template v-slot="scope">
                <!-- i1对应的是items的index -->
              <el-row :class="['bdbottom', i1===0? 'bdtop':'','vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
                   <!-- 渲染一级标题 -->
                  <el-col :span="5">
                      <el-tag closable @close="removeRightsById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                  </el-col>
               <!-- 渲染二级三级标题 -->
                  <el-col :span="19">
                      <el-row :class="[i2===0? '':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                          <!-- 渲染二级标题 -->
                          <el-col :span="6">
                            <el-tag closable type="success" @close="removeRightsById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                            <i class="el-icon-caret-right"></i>
                          </el-col>
                          <!-- 渲染三级标题-->
                          <el-col :span="18">
                            <el-tag v-for="(item3) in item2.children" :key="item3.id" closable="" type="warning" @close="removeRightsById(scope.row,item3.id)">
                              {{item3.authName}}
                            </el-tag>
                          </el-col>
                      </el-row>
                  </el-col>
              </el-row>
            </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
            <template v-slot="scope">
            <el-button v-model="scope.row.id" type="primary" icon="el-icon-edit" size="mini" @click="showroleeditdialog(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="showroledeletedialog(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showsetrightdialog(scope.row)">分配权限</el-button>
            </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 展示分配权限对话框 -->
    <el-dialog title="分配权限"
    v-model="showsetrightdialogvisible"
    width="50%" @close="treeclosedialog">
   <!-- 树形组件 data指定数据源 props绑定属性-->
    <el-tree
  :data="rightslist"
  :props="treeprops"
  node-key="id"
  :default-checked-keys="defaltkeys"
  show-checkbox
  ref="treeref"
  default-expand-all>
</el-tree>
    <template #footer>
    <span class="dialog-footer">
      <el-button @click="showsetrightdialogvisible = false">取 消</el-button>
      <el-button type="primary" @click="allotrights">确 定</el-button>
    </span>
  </template>
</el-dialog>
  <!-- 展示编辑对话框 -->
<el-dialog title="编辑角色信息" v-model="showseteditdialogvisible" width="50%"  @close="editroledialogreset">
      <el-form :model="editroleForm" :rules="editroleFormrules" ref="editroleFormref" label-width="70px">
        <el-form-item label="角色名称" prop="roleName" label-width="100px">
          <el-input v-model="editroleForm.roleName">
          </el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" label-width="100px">
          <el-input v-model="editroleForm.roleDesc">
          </el-input>
        </el-form-item>
  </el-form>
        <template #footer>
        <span class="dialog-footer">
          <el-button @click="showseteditdialogvisible = false">取 消</el-button>
          <el-button type="primary" @click="editrolesform">确 定</el-button>
        </span>
      </template>
</el-dialog>
<!-- 添加角色时的对话框 -->
<el-dialog title="添加角色" v-model="showaddroledialogvisible" width="50%" @close="addroledialogreset">
      <el-form :model="addroleForm" :rules="addroleFormrules" ref="addroleFormref" label-width="70px">
        <el-form-item label="角色名称" prop="roleName" label-width="100px">
          <el-input v-model="addroleForm.roleName">
          </el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" label-width="100px">
          <el-input v-model="addroleForm.roleDesc">
          </el-input>
        </el-form-item>
  </el-form>
        <template #footer>
        <span class="dialog-footer">
          <el-button @click="showaddroledialogvisible = false">取 消</el-button>
          <el-button type="primary" @click="addrolesformsure">确 定</el-button>
        </span>
      </template>
</el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      rolelist: [],
      rightslist: [],
      showsetrightdialogvisible: false,
      showseteditdialogvisible: false,
      showaddroledialogvisible: false,
      treeprops: {
        children: 'children',
        label: 'authName'
      },
      defaltkeys: [],
      //   当前角色的id
      roleid: '',
      editroleForm: '',
      addroleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 增加角色规则
      addroleFormrules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      },
      // 编辑角色规则
      editroleFormrules: {
        roleName: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    //   获取角色数据
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.console.error('获取用户列表失败')
      this.rolelist = res.data
      console.log(this.rolelist)
    },
    // 根据id删除对应的权限
    async removeRightsById(role, rightid) {
      const confirmresult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmresult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightid}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      // 刷新列表 会导致打开的窗口被冠上
      // this.getRoleList()
      // 解决办法
      role.children = res.data
    },
    // 获取所有权限列表
    async showsetrightdialog(role) {
      // 获取当前role的id
      this.roleid = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
      this.rightslist = res.data
      // 显示对话框
      console.log(this.rightslist)
      //   递归调用获取三级节点
      this.getleafkeys(role, this.defaltkeys)
      this.showsetrightdialogvisible = true
    },
    // 通过递归获取所有三级权限的值，并传给defaltkeys
    getleafkeys(node, arr) {
      // 如果当前节点是三级节点，name就没有children，可以直接把节点的id传给他
      if (!node.children) {
        return arr.push(node.id)
      }
      // 如果不是，则递归调用
      node.children.forEach(item => {
        this.getleafkeys(item, arr)
      })
    },
    // 当关闭树形结构的窗口时，对权限一选择的进行清空
    treeclosedialog() {
      this.defaltkeys = []
    },
    // 获取重新更改后的权限
    async allotrights() {
      const keys = [...this.$refs.treeref.getCheckedKeys(), ...this.$refs.treeref.getHalfCheckedKeys()]
      //   console.log(keys)
      // 将数组转为字符串
      const keystr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleid}/rights`, { rids: keystr })
      if (res.meta.status !== 200) return this.$message.error('获取更新后的权限失败')
      this.getRoleList()
      this.showsetrightdialogvisible = false
    },
    // 展示编辑对话框
    async showroleeditdialog(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取角色失败')
      this.editroleForm = res.data
      this.showseteditdialogvisible = true
    },
    // 编辑角色信息点击确定重新上传
    editrolesform() {
      this.$refs.editroleFormref.validate(async valid => {
        const { data: res } = await this.$http.put('roles/' + this.editroleForm.roleId, { roleName: this.editroleForm.roleName, roleDesc: this.editroleForm.roleDesc })
        if (res.meta.status !== 200) return this.$message.error('编辑角色失败')
        this.$message.success('编辑角色成功')
        // this.editroleForm = res.data
        this.getRoleList()
        this.showseteditdialogvisible = false
      })
    },
    // 添加角色对话框
    addroledialog() {
      this.showaddroledialogvisible = true
    },
    // 点击增加角色确定按钮，对表单域验证，并提交
    addrolesformsure() {
      this.$refs.addroleFormref.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addroleForm)
        if (res.meta.status !== 201) return this.$message.error('增加角色失败')
        this.$message.success('增加角色成功')
        this.getRoleList()
        this.showaddroledialogvisible = false
      })
    },
    // 关闭添加角色对话框时，对对话框进行重置
    addroledialogreset() {
      this.$refs.addroleFormref.resetFields()
    },
    // 关闭编辑角色对话框时，对对话框进行重置
    editroledialogreset() {
      this.$refs.editroleFormref.resetFields()
    },
    // 点击删除，显示删除用户对话框
    async showroledeletedialog(id) {
      const confirmresult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmresult !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.getRoleList()
      this.$message.success('删除用户成功')
    }
  }
}
</script>
<style lang="less" scoped>
</style>
